package com.example.zhinongbao.Fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.zhinongbao.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class FriendCircleFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friend_circle, container, false);

        // 初始化ViewPager2和TabLayout
        ViewPager2 viewPager = view.findViewById(R.id.viewPager);
        TabLayout tabLayout = view.findViewById(R.id.tabLayout);

        // 设置ViewPager2的Adapter
        viewPager.setAdapter(new FriendsCirclePagerAdapter(this));

        // 关联TabLayout和ViewPager2
        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(position == 0 ? "关注" : "最新")
        ).attach();

        // 初始化发布按钮
        FloatingActionButton fabPost = view.findViewById(R.id.fabPost);
        fabPost.setOnClickListener(v -> {
            FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, new PostFragment());
            transaction.addToBackStack("post_fragment");
            transaction.commit();
        });

        // 初始化个人资料按钮点击事件
        view.findViewById(R.id.btnProfile).setOnClickListener(v -> {
            // 通过底部导航的选中事件触发切换
            BottomNavigationView navView = requireActivity().findViewById(R.id.bottom_navigation);
            navView.setSelectedItemId(R.id.profile); // 必须与menu.xml中的id一致
        });

        return view;
    }

    // 内部类：ViewPager2的Adapter
    private static class FriendsCirclePagerAdapter extends FragmentStateAdapter {
        public FriendsCirclePagerAdapter(@NonNull Fragment fragment) {
            super(fragment);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return position == 0 ? new FollowFragment() : new LatestFragment();
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }
}